import {messages, deepCopy} from "share/common";
import React from 'react'
import { Form, Input, Button, message, InputNumber } from 'antd'
import workCalenderService from 'containers/setting/work-calendar/work-calendar.service';
import Permission from 'components/template/permission';
import 'styles/setting/work-calendar/new-work-calendar.scss';
import InputLanguage from 'components/template/input-language'

const FormItem = Form.Item;
class NewWorkCalendar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      permissionData: {
        range: 'ALL',
        value: []
      }
    };
  }

  handleSave = (e) => {
    const { params } = this.props;
    const editMode = !!params.calendarId;
    const { calendarCode } = this.props.params;
    const { permissionData } = this.state;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let data = deepCopy(values);
        if (permissionData.range === 'ALL') {
          data.common = true;
          data.userGroupIds = [];
        } else {
          data.common = false;
          data.userGroupIds = permissionData.value.map(item=> {return item.id});
        }
        data.calendarName = values.calendarName.name;
        data.i18n = {};
        data.i18n.calendarName = values.calendarName.i18n;
        this.setState({loading: true});
        if (!editMode) {
          workCalenderService.copyCalendarWithCalendarCode(calendarCode, data).then((res)=>{
            this.setState({loading: false});
            message.success(messages('basic-11.key179')/*复制成功*/);
            this.props.close(data.calendarCode)
          }).catch((e)=>{
            if(e.response){
              message.error(`${e.response.data.message}`);
            }
            this.setState({loading: false});
          })
        } else {
          data.calendarId = params.calendarId;
          data.tenantId = params.tenantId;
          workCalenderService.updateCalendarInfo(data).then((res)=>{
            this.setState({loading: false});
            message.success(messages('basic-11.key152')/*更新成功*/);
            this.props.close()
          }).catch((e)=>{
            if(e.response){
              message.error(`${e.response.data.message}`);
            }
            this.setState({loading: false});
          })
        }
      }
    });
  };

  componentWillMount(){
    let permissionData = {
      range: 'ALL',
      value: []
    };
    const { common, userGroups, calendarId } = this.props.params;
    const editMode = !!calendarId;
    if(!common && editMode) {
      permissionData.range = 'PERSON_GROUP';
      permissionData.value = userGroups;
    }
    this.setState({
      permissionData
    })
  }

  permissionOnChange = (data) => {
    this.setState({ permissionData: data })
  };

  render() {
    const { params } = this.props;
    const editMode = !!params.calendarId;
    const { getFieldDecorator } = this.props.form;
    const { permissionData, loading } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16, offset: 1 },
    };
    return (
      <div className="new-work-calendar">
        <Form className="new-form" onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label={messages('basic-11.key180')/*日历编码*/}>
            {getFieldDecorator('calendarCode', {
              rules: [{
                required: true,
                message: messages('common.please.input')/*请输入*/
              }],
              initialValue: editMode ? params.calendarCode : ''
            })(
              <Input disabled={editMode} placeholder={messages('common.please.input')/*请输入*/}></Input>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('basic-11.key181')/*日历名称*/}>
            {getFieldDecorator('calendarName', {
              rules: [{
                required: true,
                message: messages('common.please.input')/*请输入*/
              }],
              initialValue: editMode ? { name: params.calendarName, i18n: params.i18n ? params.i18n.calendarName : [] } : {}
            })(
              <InputLanguage/>
            )}
          </FormItem>
          <FormItem label={messages('basic-11.key182')/*优先级*/} {...formItemLayout}>{
            getFieldDecorator('priority', {
              message: messages('basic-11.key90')/*请输入temp2*/,
              rules: [{
                required: true,
                message: messages('basic-11.key90')/*请输入temp2*/,
              }],
              initialValue: editMode ? params.priority : ''
            })(
              <InputNumber
                placeholder={messages('basic-11.key90')/*请输入temp2*/}
                min={1}
                precision={0}
                max={999}
                style={{width: '66%'}}
              />
            )
          }
          </FormItem>
          <FormItem {...formItemLayout} label={messages('basic-11.key183')/*说明*/}>
            {getFieldDecorator('description', {
              initialValue: editMode ? params.description : ''
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/}></Input>
            )}
          </FormItem>
          <Permission formItemLayout={formItemLayout}
                      hidden={['DEPARTMENT']}
                      value={permissionData}
                      onChange={this.permissionOnChange}
          />
          <div className="footer-operate" style={{backgroundColor:'#ffffff', left: '0'}}>
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')/*保存*/}</Button>
            <Button onClick={() => {this.props.close()}}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

const WrappedNewWorkCalendar = Form.create()(NewWorkCalendar);

export default WrappedNewWorkCalendar;
